package com.bw.myrouter_compiler;

import com.bw.myrouter_annotation.MyRoute;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;

/**
 * 采用apt技术得到MyRoute注解，并写入文件
 */
@AutoService(Process.class)
public class RouteProcessor extends AbstractProcessor {
    @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment env) {
        System.out.println("RouteProcessor started!");
        // 1. 收集所有被 @Route 注解的类
        Set<? extends Element> elements = env.getElementsAnnotatedWith(MyRoute.class);
        for (Element element : elements) {
            if (element.getKind() != ElementKind.CLASS) {
                continue;
            }
            TypeElement typeElement = (TypeElement) element;
            MyRoute route = typeElement.getAnnotation(MyRoute.class);
            String path = route.path();
            String className = typeElement.getQualifiedName().toString();
            System.out.println("path: " + path);
            // 2. 生成 Java 代码（路由表）
            String group = path.split("/")[1]; // 提取组名，如 "/app/main" -> "app"
            String fileName = "RouteTable$$" + group; // 生成类名，如 RouteTable$$app

            // 使用 JavaPoet 生成代码
            // 生成方法: public static void loadInto(Map<String, Class<?>> routes)
            MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("loadInto")
                    .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                    .addParameter(Map.class, "routes");
            // 生成代码: routes.put("/app/main", AppMainActivity.class)
            methodBuilder.addStatement(
                    "routes.put($S, $T.class)",
                    path,
                    ClassName.get(typeElement)
            );
            // 生成类
            TypeSpec routeTable = TypeSpec.classBuilder(fileName)
                    .addModifiers(Modifier.PUBLIC)
                    .addMethod(methodBuilder.build())
                    .build();

            // 3. 写入文件
            try {
                JavaFile.builder("com.example.router", routeTable)
                        .build()
                        .writeTo(processingEnv.getFiler());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        return true;
    }
}
